package com.hsh.learning.thread;

import lombok.Data;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

/**
 * Created by root on 17-8-1.
 */

@Data
public class Worker implements Runnable{

    //任务队列
    private Queue<Object> workQueue;

    //子任务处理结果集
    private Map<String, Object> resultMap;



    //子任务处理的逻辑，在这里不作具体实现，由子类实现
    public Object handle(Object input) {
        return input;
    }


    @Override
    public void run() {
        for(;;) {
            //获取子任务
            Object input = workQueue.poll();
            if (input == null) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                    return;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //处理子任务
            Object result = handle(input);
            //将处理结果写入结果集
            resultMap.put(Integer.toString(input.hashCode()), result);
        }
    }
}
